package com.xd.common.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.List;

/**
 * @Author: 林顺
 * @Date: 2021/11/27 13:59
 */
public class JWTService {

    private final static String SECERT = "xd";

    //生成token
    public String createJWT(String username){
        String token = JWT.create()
                //接收jwt的一方
                .withAudience(username)
                //签发时间
                .withIssuedAt(new Date())
                //面向用户
                .withSubject("csdnuser")
                //过期时间
//                .withExpiresAt().
                .sign(Algorithm.HMAC256(SECERT));
        return token;
    }

    //验证token
    public boolean verifyJWT(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECERT)).build();
        try{
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            List<String> username = decodedJWT.getAudience();
            if(username != null) return true;
            return false;
        }catch (Exception E){
            return false;
        }
        return true;
    }

}
